﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf;


public class NetManager : MonoSingleton<NetManager> {

    public static int bufferSize = 1024 * 1024;
    public static int headBufferLength = 4;

    public enum NetType { TCP, UDP }

    public TCPController _tcpController;
    public UDPController _udpController;

    public NetType _netType { get; set; }

    protected override void Init()
    {
        base.Init();

        _tcpController = TCPController.Instance;
        _udpController = UDPController.Instance;

    }

    public virtual void ProcessData(byte[] data)
    {
        EventBus.Instance.BroadCastEvent<byte[]>(EventID.NETWORK_MESSAGE_RECEIVED, data);
    }

    public virtual void NetworkReady(int port,string ip)
    {
        if (_netType == NetType.TCP)
        {
            _tcpController.Connect(ip, port);
        }
        else
        {
            _udpController.NetworkPrepare((ushort)port, ip);
            _udpController.Open();
        }
    }

    public virtual void NetworkStop()
    {
        if (_netType == NetType.TCP)
        {
            _tcpController.Disconnect();
        }
        else
        {
            _udpController.Close();
        }
    }

    #region TCP_SEND

    public virtual void SendMsg(string message)
    {
        byte[] data = System.Text.Encoding.Default.GetBytes(message);
        this.SendData(data);
    }

    public virtual void SendMsg<T>(T t) where T : new()
    {
        byte[] data = Serilizer.SerializeObject(t);
        this.SendData(data);
    }

    public virtual void SendMsgWithProtoBuf<T>(T t) where T : new()
    {
        byte[] protoBfs = Protocol.ProtoBufSerialize<T>(t);
        SendData(protoBfs);
    }

    public void SendData(byte[] data)
    {
        _tcpController.SendData(data);
    }

    #endregion

    #region UDP_SEND

    public virtual void UDPSendMsg(string message,int port,string ip)
    {
        byte[] data = System.Text.Encoding.Default.GetBytes(message);
        this.UDPSend(data,port,ip);
    }

    public virtual void UDPSendMsg<T>(T t, int port, string ip) where T : new()
    {
        byte[] data = Serilizer.SerializeObject(t);
        this.UDPSend(data, port, ip);
    }

    public virtual void UDPSendMsgWithProtoBuf<T>(T t, int port, string ip) where T : new()
    {
        byte[] protoBfs = Protocol.ProtoBufSerialize<T>(t);
        this.UDPSend(protoBfs, port, ip);
    }

    public void UDPSend(byte[] data, int port, string ip)
    {
        _udpController.SendData(data, port, ip);
    }

    #endregion


    protected override void OnDestroy()
    {
        base.OnDestroy();
        TCPController.DestroyInstance();
        UDPController.DestroyInstance();

    }

}
